package cn.dgut.json;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.sql.*;
import java.util.stream.Collectors;

/**
 * @author Monster
 * Created by Sai on 2019-09-04.
 */
@WebServlet(urlPatterns = {"/json"})
public class jsonServlet extends HttpServlet {
    private static final String URL = "jdbc:h2:~/test;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String URL_MEM = "jdbc:h2:mem:test;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String URL_TCP = "jdbc:h2:tcp://localhost/~/test1;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String URL_TCP_MEM = "jdbc:h2:tcp://localhost/mem:test1;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String DRIVER = "org.h2.Driver";
    private static final String NAME = "sa";
    private static final String PASSWORD = "sa";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Jsonb jsonb = JsonbBuilder.create();
        String postJsonString = new BufferedReader(new InputStreamReader(req.getInputStream()))
                .lines().collect(Collectors.joining(System.lineSeparator()));

        StudentDTO studentDTO = jsonb.fromJson(postJsonString, StudentDTO.class);

        String stuName = studentDTO.getStuName();
        String stuNumber = studentDTO.getStuNumber();
        String stuSex = studentDTO.getStuSex();
        String stuAddress = studentDTO.getStuAddress();
        String stuEmail = studentDTO.getStuEmail();
        int stuAge=studentDTO.getStuAge();
        //伪造请求
        if (stuName==null |stuNumber==null|stuAge==0|stuSex==null|stuAddress==null|stuEmail==null){

            String jsonPerson = "{\"code\":-1,\"msg\":\"操作失败\"}";
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");

            resp.getWriter().println(jsonPerson);
        }else {
            //正确请求
            try (Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD)) {

                Statement stmt = conn.createStatement();

                stmt.executeUpdate(
                        "CREATE TABLE IF NOT EXISTS `user` (" +
                                "  `id` int(11) unsigned NOT NULL AUTO_INCREMENT," +
                                "  `stuName` varchar (50) NOT NULL," +   //姓名
                                "  `stuNumber` varchar (100) NOT NULL," +      //学号
                                "  `stuAge` int(50) NOT NULL," +        //年龄
                                "  `stuSex` varchar (50) NOT NULL," +   //性别
                                "  `stuEmail` varchar (100) NOT NULL," +  //邮箱
                                "  `stuAddress` varchar (100) NOT NULL," +  //住址
                                "  PRIMARY KEY (`id`)" +
                                ");"
                );

                String sql = "insert into `user` (`stuName`,`stuNumber`,`stuAge`,`stuSex`,`stuEmail`,`stuAddress`) values (?,?,?,?,?,?);";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1,stuName);
                ps.setString(2,stuNumber);
                ps.setInt(3,stuAge);
                ps.setString(4,stuSex);
                ps.setString(5,stuEmail);
                ps.setString(6,stuAddress);
                ps.executeUpdate();

                ResultSet rs = stmt.executeQuery("select * from user");//选择import java.sql.ResultSet;


                while (rs.next()) {
                    System.out.println(rs.getString("id") + "," + rs.getString("stuName") + "," + rs.getString("stuNumber") + "," + rs.getInt("stuAge")
                            + "," + rs.getString("stuSex")+ "," + rs.getString("stuEmail")+ "," + rs.getString("stuAddress"));
                }

                String jsonPerson = "{\"code\":0,\"msg\":\"操作成功\"}";


                resp.setContentType("application/json");
                resp.setCharacterEncoding("UTF-8");

                resp.getWriter().println(jsonPerson);


            } catch (SQLException e) {
                e.printStackTrace();
            }


        }

//        System.out.println(name);
//        System.out.println(username);
//        System.out.println(identity);
//        System.out.println(department);
//        System.out.println(email);
//        System.out.println(age);

    }
}
